import 'dart:convert';

import "package:flutter/material.dart";
import 'package:flutter/services.dart';

import 'model/DataSource.dart';
// desc: custom table
class CustomTable extends StatefulWidget {
  const CustomTable({Key key}) : super(key: key);

  @override
  _CustomTableState createState() => _CustomTableState();
}

class _CustomTableState extends State<CustomTable> {

  DataSource dataSource = new DataSource();
  Tables tables = new Tables();
  List<GoodModel> goods = [];
  // List<List<String>> test = [];

  @override
  void initState() {
    _init();
    super.initState();
  }

  _init() async {
    // 引入json
    rootBundle.loadString('assets/dataSource.json').then((value){
      setState(() {
        dataSource = DataSource.fromJson(json.decode(value));
        tables = dataSource.data.data.data.tables[0];
      });
      // print('${value}');
      // print(tables.tableRows.length);

      ///将JSON中的数据抽离，放入model
      for(int i=2; i< tables.tableRows.length; i++){
        TableRows row = tables.tableRows[i];
        GoodModel good = new GoodModel(
          index: int.parse(tables.tableRows[i].tableColumns[0].texts[0]),
          name: tables.tableRows[i].tableColumns[1].texts[0],
          unit: tables.tableRows[i].tableColumns[2].texts[0],
          number: int.parse(tables.tableRows[i].tableColumns[3].texts[0]),
          price: double.parse(
              (tables.tableRows[i].tableColumns[4].texts[0] == null ||
                  tables.tableRows[i].tableColumns[4].texts[0] == ""
              ) ? "10.0" : tables.tableRows[i].tableColumns[4].texts[0]
          ),
          // price: 80.0,
          total: double.parse(
              ( tables.tableRows[i].tableColumns[4].texts[0] == null
                  || tables.tableRows[i].tableColumns[4].texts[0] == ""
              ) ?
              "0.0" : tables.tableRows[i].tableColumns[4].texts[0]
          ),
          // total: 40.0,
          controller: new TextEditingController(text: tables.tableRows[i].tableColumns[4].texts[0])
        );
        // print(good.index);
        goods.add(good);
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text('存活盘点表', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            SizedBox(height: 20),
            Container(
              child: dataSource.success != null ? Table(
                columnWidths: <int, TableColumnWidth>{
                  0: FixedColumnWidth(30),
                  // 1: FixedColumnWidth(80),
                  2: FixedColumnWidth(60),
                  3: FixedColumnWidth(60),
                  4: FixedColumnWidth(60),
                  5: FixedColumnWidth(60),
                },
                defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                border: TableBorder.all(
                    color: Colors.grey.withOpacity(0.2),
                    width: 1.0,
                    style: BorderStyle.solid
                ),
                children: buildTableRow(goods),
              ) : SizedBox(),
            ),
            GestureDetector(
              onTap: (){
                _outPut();
              },
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.grey
                  )
                ),
                margin: EdgeInsets.only(top: 30),
                padding: EdgeInsets.only(left: 15,right: 15,top: 10,bottom: 10),
                child: Text('输出'),
              ),
            )
          ],
        ),
      ),
    );
  }


  List<TableRow> buildTableRow(List<GoodModel> modellist){
    List<TableRow> rows = [];
    rows.add(
      TableRow(
        children: buildFirstTableColumn(tables.tableRows[1])
      )
    );
    for(int i=0; i< modellist.length; i++){
      rows.add(
          TableRow(
              children: buildTableColumn(modellist[i])
          )
      );
    }
    return rows;
  }

  /// 构建表头
  List<Widget> buildFirstTableColumn(TableRows tableRows){
    List<Widget> cols = [];
    for(int i=0; i< tableRows.tableColumns.length ; i++){
      cols.add(
        buildItem(tableRows.tableColumns[i].texts == null ? ''
            : tableRows.tableColumns[i].texts[0])
        // Text('test')
      );
    }
    return cols;
  }

  // 列
  List<Widget> buildTableColumn(GoodModel goodModel){
    List<Widget> cols = [];
    cols.add(buildItem('${goodModel.index}'));
    cols.add(buildItem('${goodModel.name}'));
    cols.add(buildItem('${goodModel.unit}'));
    cols.add(buildItem('${goodModel.number}'));

    cols.add(buildTextField(goodModel.controller,goodModel));

    cols.add(buildItem('${goodModel.total}'));

    return cols;
  }

  // 插入textfield
  Widget buildTextField(TextEditingController controller, GoodModel goodModel){
    return Container(
      width: 60,
      padding: EdgeInsets.only(left: 10),
      child: TextField(
        decoration: InputDecoration(
          border: InputBorder.none
        ),
        style: TextStyle(fontSize: 14),
        keyboardType: TextInputType.number,
        controller: controller,
        onChanged: (value){
          setState(() {
            goodModel.price = double.parse(value);
            goodModel.total = double.parse(value) * goodModel.number;
          });
        },
      ),
    );
  }
  Widget buildItem(String text){
    return Container(
      padding: EdgeInsets.all(10),
      child: Center(
        child: Text(text),
      ),
    );
  }

  _outPut(){
    List<GoodModel> totalEmpty = [];
    List<GoodModel> totalNotEmpty = [];
    for(int i=0 ;i< goods.length; i++){
      if(goods[i].total == 0){
        totalEmpty.add(goods[i]);
      }else {
        totalNotEmpty.add(goods[i]);
      }
    }
    print('总价为0: ${totalEmpty.length}');
    print('总价不为0: ${totalNotEmpty.length}');
    // showToast("总价为0的长度: ${totalEmpty.length}, 总价不为0的长度: ${totalNotEmpty.length}");
    showDialog(
        context: context,
        builder: (BuildContext context){
          return Material(
            color: Colors.transparent,
            child: Container(
              color: Colors.grey.withOpacity(0.2),
              child: Align(
                child: GestureDetector(
                  onTap: (){ Navigator.pop(context); },
                  child: Container(
                    width: double.maxFinite,
                    margin: EdgeInsets.only(left: 20, right: 20),
                    height: 600,
                    color: Colors.white,
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('总价不为0: '),
                          Column(
                            children: outPrintListContent(totalNotEmpty),
                          ),
                          SizedBox(height: 20),
                          Text('总价为0: '),
                          Column(
                            children: outPrintListContent(totalEmpty),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        }
    );
  }

  outPrintListContent(List<GoodModel> list) {
    List<Widget> textList = [];
    for(int i=0; i< list.length; i++){
      textList.add(
        Text('${list[i].toString()}')
      );
    }
    return textList;
  }
}

class Good {
  int row;
  int column;
  TextEditingController controller;

  Good({
    this.row,
    this.column,
    this.controller
  });
}

class GoodModel {
  int index;
  String name;
  String unit;
  int number;
  double price;
  double total;
  TextEditingController controller;


  GoodModel({
    this.index,
    this.name,
    this.unit,
    this.number,
    this.price,
    this.total,
    this.controller
  });

  @override
  String toString() {
    // TODO: implement toString
    return '''
    {
      序号: $index
      存货名称: $name
      计量单位: $unit
      数量: $number
      单价: $price
      总价: $total
    }
    ''';
  }
}